﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using TaskManagementSystem.Middleware;

namespace TaskManagementSystem.ScheduledTask
{
    internal class ScheduledTaskManager
    {
        /// <summary>
        /// 系统启动当前服务器的排程
        /// </summary>
        internal static void Start()
        {
            ScheduledTaskCore.CurrentScheduledTask.Start();
        }

        /// <summary>
        /// 系统所有的排程
        /// </summary>
        internal static void Stop()
        {
            ScheduledTaskCore.CurrentScheduledTask.Stop();
        }

        /// <summary>
        /// 执行任务
        /// </summary>
        /// <param name="job"></param>
        internal static void ExecuteTask(Entity.SystemCronConfigData data)
        {
            ScheduledTaskCore.CurrentScheduledTask.Add(data);
        }

        /// <summary>
        /// 停止任务
        /// </summary>
        /// <param name="job"></param>
        internal static bool StopTask(Entity.SystemCronConfigData data)
        {
            return ScheduledTaskCore.CurrentScheduledTask.Stop(data);
        }

        internal static void LoadData()
        {
            var taskTypes = AppDomain.CurrentDomain.GetAssemblies()
                        .SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IScheduledTask))))
                        .ToArray();

            Data.DbContext dbContext = new Data.DbContext();
            List<Entity.SystemCronConfigData> list = new List<Entity.SystemCronConfigData>();
            foreach (var type in taskTypes)
            {
                Entity.SystemCronConfigData data = new Entity.SystemCronConfigData();
                object[] objs = type.GetCustomAttributes(typeof(ScheduledTaskAttribute), true);
                foreach (object obj in objs)
                {
                    ScheduledTaskAttribute attr = obj as ScheduledTaskAttribute;
                    if (attr != null)
                    {
                        data.JobName = attr.JobName;
                        data.JobType = (int)attr.JobType;
                        data.TimeSpan = attr.TimeSpan;
                        data.CronExpression = attr.CronExpression;
                        break;
                    }
                }

                data.IsValidity = false;
                data.JobName = string.IsNullOrWhiteSpace(data.JobName) ? type.Name : data.JobName;
                data.JobKey = type.FullName;
                data.Assembly = type.AssemblyQualifiedName;

                if (dbContext.SystemCronConfigData.Where(x => x.Assembly == data.Assembly).FirstOrDefault() == null)
                {
                    list.Add(data);
                }
            }

            dbContext.SystemCronConfigData.AddRange(list);
            dbContext.SaveChanges();
        }
    }
}